package work.coffee.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import work.coffee.connect.CloserUtil;
import work.coffee.dto.Coffee;

public class CoffeeDao {
	private Connection con;

	public CoffeeDao(Connection con) {
		this.con = con;
	}
	public void insertCoffee(Coffee cf) throws SQLException {
		String sql = "insert into coffee_fr values(?,?,?,?)";
		PreparedStatement pstmt = con.prepareStatement(sql);
		pstmt.setString(1, cf.getcNum());
		pstmt.setInt(2, cf.getcPrice());
		pstmt.setInt(3, cf.getcCount());
		pstmt.setInt(4, cf.getcMargin());
		pstmt.executeUpdate();
		CloserUtil.close(pstmt);
	}
	public ArrayList<Coffee> listItem() throws SQLException {
		ArrayList<Coffee> list = new ArrayList<>();
		String sql = "select c.cnum, c.cname, cf.cprice, cf.ccount, cf.cmargin from coffee c, coffee_fr cf where c.cnum=cf.cnum";
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();

		while (rs.next()) {
			list.add(new Coffee(rs.getString("cnum"), rs.getString("cname"), rs.getInt("cprice"), rs.getInt("ccount"), rs.getInt("cmargin")));
		}
		CloserUtil.close(rs);
		CloserUtil.close(pstmt);
		return list;
	}
	public String searchName(Coffee cf) {
		String sql = "select cname from coffee where cnum=?";
		PreparedStatement pstmt;
		ResultSet rs = null;
		String name = null;
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, cf.getcNum());
			rs = pstmt.executeQuery();
			if (rs.next()) {
				name = rs.getString(1);
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		return name;
	}
}